package com.dzf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dzf.entity.MyUser;
import com.dzf.entity.Permission;
import com.dzf.mapper.PermissionMapper;
import com.dzf.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Primary
@Service
public class LoginServiceImpl implements UserDetailsService {

    @Autowired(required = false)
    UserMapper userMapper;

    @Autowired
    PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        QueryWrapper<MyUser> wrapper = new QueryWrapper<>();
        wrapper.eq("account",s);
        MyUser user = userMapper.selectOne(wrapper);
        //访问Dao层


//        if (user==null)
//        {
//            throw  new UsernameNotFoundException("用户名不存在");
//        }

        List<Permission> list = permissionMapper.findByUserPer(user.getRole());
        List<SimpleGrantedAuthority> lst = new ArrayList<>();
        System.err.println(list);
        for(Permission per: list) {
            SimpleGrantedAuthority sga = new SimpleGrantedAuthority(per.getPermissionAuth());
            lst.add(sga);
        }

        user.setAuthorities(lst);
        System.out.println(user.getAuthorities());
        return user;
    }




}
